package com.wholesale;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.CartInfo;
import com.wholesale.beans.CorrectGoodsPrice;
import com.wholesale.datas.DbHelperAdapter;
import com.wholesale.datas.ShopCar;
import com.wholesale.utils.AsyncImageLoader;
import com.wholesale.utils.AsyncImageLoader.ImageCallback;
import com.wholesale.utils.CartCache;
import com.wholesale.utils.CartListAdapter;
import com.wholesale.utils.Constants;

public class Cart1Layout extends LinearLayout implements OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private LinearLayout bodyList;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private RelativeLayout loadingLayout;

	private boolean isDelete = false;
	private TextView totalNumView;
	private TextView totalPriceView;
	private ArrayList<ShopCar> data;

	// 构造函数
	public Cart1Layout(Context context, final ViewFlipper viewFlipper) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.cart1, this);
		bodyList = (LinearLayout) baseView.findViewById(R.id.bodyLayout);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Edit");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setText("Check out");
		rightButton.setOnClickListener(this);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("Cart");
		totalNumView = (TextView) baseView.findViewById(R.id.totalcount_text);
		totalPriceView = (TextView) baseView.findViewById(R.id.totalprice_text);
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);
		// item 单击事件
		CartListAsync cartListAsync = new CartListAsync(context);
		cartListAsync.execute((Void) null);

	}

	public void updateShopCar() {
		CartListAsync cartListAsync = new CartListAsync(context);
		cartListAsync.execute((Void) null);
	}

	// ListView 点击事件
	class GoodsOnClick implements OnClickListener {
		int index;

		public GoodsOnClick(int index) {
			this.index = index;
		}

		@Override
		public void onClick(View v) {
			if (!isDelete) {
				GoodsDetailLayout goodsDetailLayout = new GoodsDetailLayout(
						context, viewFlipper, "Cart", data.get(index)
								.getGoodsId());
				viewFlipper.addView(goodsDetailLayout);
				viewFlipper.showNext();
			}
		}

	}

	class CartListAsync extends AsyncTask<Void, Integer, ArrayList<ShopCar>> {
		ProgressDialog pdialog;

		public CartListAsync(Context context) {
			// pdialog = new ProgressDialog(context);
			// pdialog.setTitle("Loading...");
			// pdialog.setMessage("Please wait...");
			// pdialog.setCancelable(true);
			// pdialog.setButton("cancel", new DialogInterface.OnClickListener()
			// {
			// public void onClick(DialogInterface dialog, int i) {
			// dialog.cancel();
			// CartListAsync.this.cancel(true);
			// }
			// });
			// pdialog.show();
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<ShopCar> doInBackground(Void... params) {
			DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(context);
			dbHelperAdapter.open();
			data = dbHelperAdapter.getAll();
			dbHelperAdapter.close();
			return data;
		}

		@Override
		protected void onPostExecute(ArrayList<ShopCar> result) {
			initList(result);
			// pdialog.dismiss();
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	private AsyncImageLoader loader = AsyncImageLoader.getInstance();

	/**
	 * 供外部调用,根据返回值更新购物车
	 * 
	 * @param cgpLst
	 */
	public void updateList(List<CorrectGoodsPrice> cgpLst) {
		if (data != null && data.size() > 0) {
			for (CorrectGoodsPrice cgp : cgpLst) {
				for (ShopCar sc : data) {
					if (cgp.getGoodsId() == sc.getGoodsId()) {
						sc.getCartInfo().setGoodsPrice(cgp.getPrice());
					}
				}
			}
			initList(data);
		}
	}

	private void initList(ArrayList<ShopCar> result) {
		bodyList.removeAllViews();
		int totalNum = 0;
		double totalprice = 0;
		int position = 0;
		for (ShopCar shopCar : result) {
			totalNum = totalNum + shopCar.getCartInfo().getGoodsNumber();
			totalprice = totalprice + shopCar.getCartInfo().getGoodsPrice()
					* shopCar.getCartInfo().getGoodsNumber();
			Activity activity = (Activity) context;
			LayoutInflater inflater = activity.getLayoutInflater();
			final View rowView = inflater.inflate(R.layout.cartitems, null);
			final CartCache viewCache = new CartCache(rowView);
			CartInfo cartInfo = shopCar.getCartInfo();

			// Load the image and set it on the ImageView
			String imageUrl = cartInfo.getGoodsImg();
			ImageView imageView = viewCache.getGoodsImage();
			imageView.setTag(imageUrl);
			Drawable cachedImage = loader.loadDrawable(imageUrl,
					new ImageCallback() {
						public void imageLoaded(Drawable imageDrawable,
								String imageUrl) {
							((ImageView) rowView.findViewById(R.id.goodsImage))
									.setImageDrawable(imageDrawable);
							((ImageView) rowView.findViewById(R.id.goodsImage))
									.postInvalidate();
							viewCache.getGoodsImage().setImageDrawable(
									imageDrawable);
						}
					});
			if (cachedImage == null) {
				imageView.setImageResource(R.drawable.loading);
			} else {
				imageView.setImageDrawable(cachedImage);
			}
			if (isDelete) {
				viewCache.getGoodsNumber().setVisibility(View.GONE);
				viewCache.getGoodsNumberEdit().setVisibility(View.VISIBLE);
				viewCache.getGoodsNumberEdit().addTextChangedListener(
						new GoodsNumberEditWatcher(position, viewCache
								.getTotalPrice()));
				viewCache.getGoodsNumberEdit().setOnFocusChangeListener(
						new GoodsNumberEditListener(position, viewCache
								.getTotalPrice()));
				viewCache.getDeteleButton().setTag(cartInfo.getGoodsId());
				viewCache.getDeteleButton().setVisibility(View.VISIBLE);
				viewCache.getDeteleButton().setOnClickListener(
						new lvButtonListener(position));
			} else {
				viewCache.getGoodsNumber().setVisibility(View.VISIBLE);
				viewCache.getGoodsNumberEdit().setVisibility(View.GONE);
				viewCache.getDeteleButton().setVisibility(View.GONE);
				viewCache.getDeteleButton().setOnClickListener(null);
			}
			String goodsAttr = cartInfo.getGoodsAttr();
			if (goodsAttr != null && !goodsAttr.equals("")) {
				goodsAttr = goodsAttr.replaceAll(",", "\n");
				goodsAttr = goodsAttr.replaceAll(";", "\n");
				viewCache.getAttributeTextView().setText(goodsAttr);

				// String[] strs = goodsAttr.split("\n");
				// String value;
				// for (int i = 0; i < strs.length; i++) {
				// value = strs[i];
				// TextView textView = new TextView(context);
				// textView.setText(value);
				// viewCache.getGoodsColorLayout().addView(textView);
				// value = value.split(":")[1];
				// if (value.indexOf("custom size") != -1
				// || value.indexOf("Custom size") != -1
				// || value.indexOf("custom Size") != -1
				// || value.indexOf("Custom Size") != -1) {
				// i++;
				// textView = new TextView(context);
				// textView.setText(strs[i++] + "cm  " + strs[i++] + "cm");
				// viewCache.getGoodsColorLayout().addView(textView);
				// textView = new TextView(context);
				// textView.setText(strs[i++] + "cm  " + strs[i++] + "cm");
				// viewCache.getGoodsColorLayout().addView(textView);
				// }
				// }
			}
			viewCache.getGoodsName().setText(cartInfo.getGoodsName());
			viewCache.getGoodsPrice()
					.setText("US$ " + cartInfo.getGoodsPrice());
			viewCache.getGoodsNumber().setText("" + cartInfo.getGoodsNumber());
			viewCache.getGoodsNumberEdit().setText(
					"" + cartInfo.getGoodsNumber());
			viewCache.getTotalPrice().setText(
					"US$ "
							+ getTwoDecimal(cartInfo.getGoodsPrice()
									* cartInfo.getGoodsNumber()));
			rowView.setOnClickListener(new GoodsOnClick(position));
			bodyList.addView(rowView);
			position = position + 1;
		}
		totalNumView.setText("" + totalNum);
		totalPriceView.setText("" + getTwoDecimal(totalprice));
	}

	private void sendBroadcastForShopCar() {
		Intent myIntent = new Intent();// 创建Intent对象
		myIntent.setAction("com.wholesale.utils.UpdateUIService");
		myIntent.putExtra("cmd", Constants.CMD_DELETECAR_SERVICE);
		myIntent.putExtra("from", "com.wholesale.CartLayout");
		((Activity) getContext()).sendBroadcast(myIntent);
	}

	private double getTwoDecimal(double d) {
		BigDecimal bd = new BigDecimal(d);
		double result = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) ((Activity) getContext())
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		// InputMethodManager imm = (InputMethodManager)((Activity)
		// getContext()).getSystemService(Context.INPUT_METHOD_SERVICE);
		switch (v.getId()) {
		case R.id.leftBtn:

			// imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
			// InputMethodManager.HIDE_NOT_ALWAYS);

			imm.hideSoftInputFromWindow(leftButton.getWindowToken(), 0);

			if (data.size() > 0) {
				if (isDelete) {
					int count = data.size();
					DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(
							context);
					dbHelperAdapter.open();
					for (int i = 0; i < count; i++) {
						dbHelperAdapter.update(data.get(i));
					}
					dbHelperAdapter.close();
					sendBroadcastForShopCar();
					isDelete = false;
				} else {
					isDelete = true;
				}
				if (isDelete) {
					leftButton.setText("Update");
				} else {
					leftButton.setText("Edit");
				}
				// cartListAdapter.setDelete(isDelete);
				// cartListAdapter.notifyDataSetChanged();
				// bodyList.postInvalidate();
				initList(data);
			}
			// if (isDelete) {
			// isDelete = false;
			// } else {
			// isDelete = true;
			// }
			// initList(data);
			// if (isDelete) {
			// leftButton.setText("Update");
			// } else {
			// leftButton.setText("Edit");
			// }
			break;
		case R.id.rightBtn:

			// imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
			// InputMethodManager.HIDE_NOT_ALWAYS);
			// InputMethodManager imm = (InputMethodManager)((Activity)
			// getContext()).getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(rightButton.getWindowToken(), 0);
			if (data.size() > 0) {
				if (!isDelete) {
					if (Constants.userInfo == null) {
						UserLoginLayout userLoginLayout = new UserLoginLayout(
								context, viewFlipper);
						viewFlipper.addView(userLoginLayout);
						viewFlipper.showNext();
					} else {
						if (data != null && data.size() > 0) {
							CheckOutLayout checkOutLayout = new CheckOutLayout(
									context, viewFlipper, data);
							viewFlipper.addView(checkOutLayout);
							viewFlipper.showNext();
						}
					}
				} else {
					dialog("Infomation",
							"Current is editing cart, please update cart first.");
				}
			}
			break;
		default:
			break;
		}

	}

	public void dialog(String title, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Confirm",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	class GoodsNumberEditWatcher implements TextWatcher {
		private int position;
		private int temp;
		private int beforeText;
		private int afterText;
		private ShopCar shopCar;
		private TextView curTotal;

		GoodsNumberEditWatcher(int pos, final TextView total) {
			position = pos;
			this.curTotal = total;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (s.toString().equals("")) {
				temp = 1;
			} else {
				temp = Integer.parseInt(s.toString());
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			if (s.toString().equals("")) {
				beforeText = 1;
			} else {
				beforeText = Integer.parseInt(s.toString());
			}
		}

		@Override
		public void afterTextChanged(Editable s) {
			int now = 1;
			if (!s.toString().equals("") && !s.toString().equals("0")) {
				now = Integer.parseInt(s.toString().trim());
				if (data.get(position).getCartInfo().getGoodsNumber() != now
						&& isDelete) {
					int before = beforeText;
					// CartListAdapter.this.getItem(position).getCartInfo()
					// .setGoodsNumber(temp);
					data.get(position).getCartInfo().setGoodsNumber(now);
					double price = data.get(position).getCartInfo()
							.getGoodsPrice();
					int totalNum = Integer.parseInt(totalNumView.getText()
							.toString().trim());
					totalNum = totalNum - before + now;
					double totalPri = Double.parseDouble(totalPriceView
							.getText().toString().trim());
					totalPri = totalPri + (now - before) * price;
					totalNumView.setText("" + totalNum);
					totalNumView.postInvalidate();
					totalPriceView.setText("" + getTwoDecimal(totalPri));
					totalPriceView.postInvalidate();
					curTotal.setText("US$ " + getTwoDecimal(now * price));
					curTotal.postInvalidate();
					beforeText = now;
				}
			} else {
				data.get(position).getCartInfo().setGoodsNumber(now);
			}
		}
	}

	class lvButtonListener implements OnClickListener {
		private int position;

		lvButtonListener(int pos) {
			position = pos;
		}

		@Override
		public void onClick(View v) {
			int vid = v.getId();
			DeleteFavoriteListAsync deleteFavoriteListAsync = new DeleteFavoriteListAsync(
					context, position);
			deleteFavoriteListAsync.execute(data.get(position));
		}
	}

	class GoodsNumberEditListener implements OnFocusChangeListener {
		private int position;
		private ShopCar shopCar;
		private TextView curTotal;

		GoodsNumberEditListener(int pos, final TextView total) {
			position = pos;
			this.shopCar = data.get(position);
			this.curTotal = total;
		}

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			EditText temp = (EditText) v;
			String s = temp.getText().toString();
			if (!hasFocus) {
				if (s.equals("") || s.equals("0")) {
					int now = 1;
					temp.setText("" + now);
					int before = data.get(position).getCartInfo()
							.getGoodsNumber();
					data.get(position).getCartInfo().setGoodsNumber(now);
					double price = data.get(position).getCartInfo()
							.getGoodsPrice();
					int totalNum = Integer.parseInt(totalNumView.getText()
							.toString().trim());
					totalNum = totalNum - before + now;
					double totalPri = Double.parseDouble(totalPriceView
							.getText().toString().trim());
					totalPri = totalPri + (now - before) * price;
					totalNumView.setText("" + totalNum);
					totalNumView.postInvalidate();
					totalPriceView.setText("" + getTwoDecimal(totalPri));
					totalPriceView.postInvalidate();
					curTotal.setText("US$ " + getTwoDecimal(now * price));
					curTotal.postInvalidate();
				}
			}
		}
	}

	class DeleteFavoriteListAsync extends AsyncTask<ShopCar, Integer, Boolean> {
		ProgressDialog pdialog;
		int position;

		public DeleteFavoriteListAsync(Context context, int position) {
			pdialog = new ProgressDialog(context);
			this.position = position;
			pdialog.setTitle("Deleteing...");
			pdialog.setMessage("Please wait...");
			pdialog.setCancelable(true);
			pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					dialog.cancel();
					DeleteFavoriteListAsync.this.cancel(true);
				}
			});
			pdialog.show();
		}

		@Override
		protected Boolean doInBackground(ShopCar... params) {
			Boolean result = false;
			DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(context);
			dbHelperAdapter.open();
			result = dbHelperAdapter.delete(params[0]);
			dbHelperAdapter.close();
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				ShopCar shopCar = (ShopCar) data.get(position);
				int num = Integer.parseInt(totalNumView.getText().toString()
						.trim());
				num = num - shopCar.getCartInfo().getGoodsNumber();
				totalNumView.setText("" + num);
				double price = Double.parseDouble(totalPriceView.getText()
						.toString().trim());
				price = price - shopCar.getCartInfo().getGoodsPrice()
						* shopCar.getCartInfo().getGoodsNumber();

				totalPriceView.setText("" + getTwoDecimal(price));
				// CartListAdapter.this.remove(CartListAdapter.this
				// .getItem(position));
				data.remove(position);
				initList(data);
				Intent myIntent = new Intent();// 创建Intent对象
				myIntent.setAction("com.wholesale.utils.UpdateUIService");
				myIntent.putExtra("cmd", Constants.CMD_DELETECAR_SERVICE);
				myIntent.putExtra("from", "com.wholesale.utils.CartListAdapter");
				((Activity) context).sendBroadcast(myIntent);
			} else {
				AlertDialog.Builder builder = new Builder(context);
				builder.setTitle("Error");
				builder.setMessage("Delete fail ");
				builder.setPositiveButton("Confirm",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
			pdialog.dismiss();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
}
